<script setup>
import { GetSettldisburseAPI } from '@/api/common/index.js'

const { proxy } = getCurrentInstance()

// 获取字典方法
const {
  bill_state, // 票据状态
  goods_invoice_type, // 发票种类
} = proxy.useDict('bill_state', 'goods_invoice_type')

// 列表数据
const tableData = ref([])

// 按钮
const buttonList = ref([])

// 表单ref
const addFormRef = ref(null)

// 支出下拉数据
const settldisburse = ref([])

// 列表枚举
const column = ref([
  { label: '发票种类', prop: 'invoiceSpeciesDict' },
  { label: '开票日期', prop: 'invoiceTime' },
  { label: '发票号码', prop: 'invoiceNumber' },
  { label: '发票代码', prop: 'invoiceCode' },
  { label: '票据状态', prop: 'state', showText: false },
  { label: '客户', prop: 'clientName' },
  { label: '收支类别', prop: 'invoiceTypeDict', showText: false },
  { label: '合计金额', prop: 'invoiceTotalAmount' },
  { label: '合计税额', prop: 'invoiceTotalRate' },
  { label: '价税合计', prop: 'invoiceTotalPrice' },
  { label: '备注', prop: 'remark' },
  { label: '开票人', prop: 'createBy' },
  { label: '审核人', prop: 'examineBy' },
  { label: '审核时间', prop: 'examineTime' },
  { label: '操作', prop: 'x', width: '250' },
])

// 合计计算
const amountList = ref([
  'invoiceTotalAmount',
  'invoiceTotalRate',
  'invoiceTotalPrice',
])

// 状态
const state = reactive({
  treeLoading: false,
  singleDis: false, // 多选后禁用
  multipleDis: false, // 没有选择后禁用
  loading: false, // 列表加载状态
  btnLoading: false, // 按钮加载状态
  isShow: false, // 弹窗状态
  examineShow: false, // 审核弹窗
  title: '新增', // 弹窗标题
  total: 0, // 列表总量
  ids: '', // 列表选择的id
})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 查询条件 枚举
const selectList = ref([
  { type: '日期范围' },
  { label: '发票号码', model: 'invoiceNumber', type: '输入框' },
  { label: '发票代码', model: 'invoiceCode', type: '输入框' },
  {
    label: '发票种类',
    model: 'invoiceSpecies',
    type: '下拉单选',
    opt: goods_invoice_type,
  },
  { label: '收支类型', model: 'invoiceType', type: '下拉单选', opt: [] },
  {
    label: '票据状态',
    model: 'invoiceStatus',
    type: '下拉单选',
    opt: bill_state,
  },
  { label: '客户名称', model: 'clientName', type: '输入框' },
])

// 表单
const ruleForm = ref({})

// 初始化按钮 原因：没有办法做到完全响应 每次事件触发再次执行
const initBtn = () => {
  buttonList.value = [
    { type: 'add', hasPermi: 'system:inItemTax:add' },
    {
      type: '提交审核',
      disabled: state.multipleDis,
      hasPermi: 'system:inItemTax:remove',
    },
    {
      type: '撤销审核',
      disabled: state.multipleDis,
      hasPermi: 'system:inItemTax:revoke',
    },
    {
      type: '审核',
      disabled: state.multipleDis,
      hasPermi: 'system:inItemTax:examine',
    },
    {
      type: 'export',
      disabled: state.multipleDis,
      hasPermi: 'system:inItemTax:export',
    },
    {
      type: '打印',
      disabled: state.multipleDis,
      hasPermi: 'system:inItemTax:print',
    },
  ]
}

// 新增弹窗
const addDic = () => {
  state.isShow = true
  state.title = '新增'
}

// 修改弹窗
const editDic = async (id) => {
  try {
    proxy.loading('请稍后')
    const { data: res } = await GetViewAPI(id)
    ruleForm.value = res
    state.title = '修改'
    state.isShow = true
  } catch {
  } finally {
    proxy.closeLoading()
  }
}

// 查看弹窗
const lookDic = async (id) => {
  try {
    proxy.loading('请稍后')
    const { data: res } = await GetViewAPI(id)
    ruleForm.value = res
    state.title = '查看'
    state.isShow = true
  } catch {
  } finally {
    proxy.closeLoading()
  }
}

// 审核弹窗
const examineDic = async () => {
  if (state.rows[0].invoiceStatus != 2 && state.rows[0].invoiceStatus != 3) {
    proxy.warningMsg('只有待审核和审核中状态才能审核！')
    return
  }

  try {
    proxy.loading('请求中,请稍后')
    const { data: res } = await GetViewAPI(state.ids[0])
    ruleForm.value = res
    state.title = '审核'
    state.examineShow = true
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 新增提交
const addSub = async () => {
  try {
    state.btnLoading = true
    const result = await addFormRef.value.submit()
    if (!result) return
    await AddDataAPI(result)
    closeDic()
    proxy.successMsg('新增成功!')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

// 修改提交
const editSub = async () => {
  try {
    state.btnLoading = true
    const result = await addFormRef.value.submit()
    if (!result) return
    await EditDataAPI(result)
    closeDic()
    proxy.successMsg('修改成功!')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

// 提交审核
const subExamine = async () => {
  proxy.loading('请求中,请稍后')
  try {
    await SubmitReviewAPI(state.ids[0])
    proxy.successMsg('操作成功!')
    getList()
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 撤销审核
const revoke = async () => {
  if (state.rows[0].invoiceStatus != 2) {
    proxy.warningMsg('只有待审核状态才能撤销审核！')
    return
  }

  proxy.loading('请求中,请稍后')
  try {
    await DeleteReviewAPI(state.ids[0])
    proxy.successMsg('操作成功!')
    getList()
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 审核提交保存
const eamineSub = async (val) => {
  try {
    state.btnLoading = true
    const result = await addFormRef.value.submit()
    if (!result) return
    await ExamineAPI({
      invoiceIntoId: state.ids[0],
      auditOpinion: result.auditOpinion,
      auditState: val,
    })
    closeDic()
    proxy.successMsg('审核成功!')
  } catch (err) {
    console.error(err)
  } finally {
    state.btnLoading = false
  }
}

// 删除
const remove = async (id) => {
  proxy.loading('请求中,请稍后')
  try {
    await DelDataAPI(id)
    getList()
    proxy.successMsg('删除成功!')
  } catch (err) {
    console.error(err)
  } finally {
    proxy.closeLoading()
  }
}

// 打印
const printFun = () => {}

// 导出
const exportFun = () => {}

// 弹窗取消和xx事件
const closeDic = () => {
  state.isShow = false
  state.examineShow = false
  ruleForm.value = {}

  getList()
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = ({ ids, row }) => {
  state.ids = ids
  state.rows = row
  state.multipleDis = !row.length
  state.singleDis = row.length != 1
  initBtn()
}
handleSelectionChange({ ids: [], row: [] })

// 查询条件
const selectSubmit = (val) => {
  Object.keys(val).forEach((keyItem) => (query[keyItem] = val[keyItem]))
  getList()
}

// 获取列表
const getList = async () => {
  state.loading = true
  try {
    const result = await GetListAPI(query)
    tableData.value = result.rows
    state.total = result.total
  } catch {
  } finally {
    state.loading = false
  }
}
getList()

// 获取
const initData = async () => {
  const { data: result } = await GetSettldisburseAPI()
  settldisburse.value = result
  selectList.value[4].opt = result
}

initData()

const fileValue = ref({
  img: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  fileUrl:
    'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100.pdf',
})
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" />

    <el-card>
      <el-form
        ref="addFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="点动开关">
          <p-select
            isValue
            :option="[
              { label: '测试1', value: 1 },
              { label: '测试2', value: 2 },
            ]"
          />
        </el-form-item>
        <el-form-item label="点动开关">
          <p-switch />
        </el-form-item>

        <el-form-item label="图片上传">
          <p-imageUpload v-model="fileValue.img" />
        </el-form-item>
        <el-form-item label="文件上传">
          <p-fileUpload v-model="fileValue.fileUrl" />
        </el-form-item>
        <el-form-item label="图片预览">
          <p-imagePreview
            src="https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <!-- 按钮组件 -->
      <p-button
        :list="buttonList"
        @add="addDic"
        @remove="remove"
        @examine="examineDic"
        @revoke="revoke"
        @sub-examine="subExamine"
        @export="exportFun"
        @print="printFun"
      />
      <!-- 表格数据 -->
      <p-table
        className="tableClass"
        keyId="invoicePinId"
        summary
        :loading="state.loading"
        :data="tableData"
        :column="column"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        :total="state.total"
        :amountList="amountList"
        @change="handleSelectionChange"
        @pagination="getList"
      >
        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.label == '票据状态'"
            :value="record.invoiceStatus"
            :options="bill_state"
          />

          <p-operate
            v-if="column.label == '操作'"
            hasPermi="finance:inItemTax"
            :removeDis="record.invoiceStatus != 1 && record.invoiceStatus != 4"
            :editDis="record.invoiceStatus != 1 && record.invoiceStatus != 4"
            @remove="remove(record.invoicePinId)"
            @edit="editDic(record.invoicePinId)"
            @look="lookDic(record.invoicePinId)"
          >
            <div>
              <el-button icon="Pointer" type="warning" size="small"
                >撤销审核</el-button
              >
              <el-button icon="RefreshLeft" type="warning" size="small"
                >提交审核</el-button
              >
              <el-button icon="View" type="warning" size="small"
                >审核</el-button
              >
              <el-button icon="Document" type="primary" size="small"
                >打印</el-button
              >
            </div>
          </p-operate>
        </template>
      </p-table>
    </el-card>
  </div>
</template>
<style scoped lang="scss"></style>
